package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class Utils {

    public static WebDriver driver;
    public static String url;
    public WebDriverWait wait;

    public Utils(String url) {
        //调用driver对象
        driver = createDriver();
        wait = new WebDriverWait(driver,Duration.ofSeconds(3));
        driver.get(url);
    }

    /**
     * 获取驱动对象
     * @return
     */
    public static WebDriver createDriver(){
        if (driver == null){
            //驱动管理程序下载驱动
            WebDriverManager.edgedriver().setup();
            //浏览器配置对象
            EdgeOptions options = new EdgeOptions();
            //允许访问所有链接
            options.addArguments("--remote-allow-origins=*");
            //打开浏览器
            driver = new EdgeDriver(options);
            //设置隐式等待3秒
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));

        }
        return driver;
    }

    //屏幕截图
    public void screenCapture(String src) throws IOException {
        TakesScreenshot screenshot = ((TakesScreenshot) driver);
        File file = screenshot.getScreenshotAs(OutputType.FILE);

        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");

        String dirTime = sim1.format(System.currentTimeMillis());
        String fileTime = sim2.format(System.currentTimeMillis());

        String fileName = "./src/test/java/images" + driver + "/" + src + "_" + fileTime + ".png";

        FileUtils.copyFile(file,new File(fileName));
    }

    //将String类型的数字转为int
    public static int transition(String str){
        int num = Integer.parseInt(str);
        return num;
    }

}
